import React, { Component } from 'react';
import BaseComponent from '@/components/BaseComponent';
import styled from 'styled-components';
import { Badge, Button, Calendar, Card, Col, Input, Row, Select } from 'antd';
import Create from '@/pages/Project/Journal/Create';
import { connect } from 'dva';
import Preview from '@/pages/Project/Journal/Preview';
import { date } from 'mockjs/src/mock/random/date';

const JournalDiv = styled.div`
  .header-right {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
  }

  .body-card {
    margin-top: 16px;
  }

  .events {
    padding-left: 0;
  }
`;

@connect(({ projectjournal, user, loading }) => ({
  currentUser: user.currentUser,
  isCreating: loading.effects['projectjournal/create'],
  isDeling: loading.effects['projectjournal/deleteJournalById'],
}))
class Journal extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      searchDate: new Date(),
      // 新增
      createVisible: false,
      // 详情
      previewVisible: false,
      // 日志数据
      journals: {},
      // 项目列表
      projects: [],
      // 选中的数据
      record: {},
    };
  }

  componentDidMount() {
    this.queryAllProjects();
    this.selectAllJournalsByUser();
  }

  /**
   * 获取所有的项目列表
   */
  queryAllProjects = () => {
    this.execHttp('projectjournal/queryAllProjects', {}).then(resp => {
      const { success, data } = resp;
      if (success) {
        const { projects } = data;
        this.setState({
          projects: projects,
        });
      }
    });
  };

  /**
   * 获取日志数据
   */
  selectAllJournalsByUser = () => {
    const { searchDate } = this.state;

    const date = `${searchDate.getFullYear()}-${searchDate.getMonth() + 1}-${searchDate.getDate()}`;

    const create_by = this.props.currentUser['id'];
    const hide = this.loadingMessage('数据加载中...');

    this.execHttp('projectjournal/selectAllJournalsByUser', {
      create_by: create_by,
      search_date: date,
    })
      .then(value => {
        hide();
        const { data, success } = value;
        if (success) {
          const { journals } = data;
          this.setState({
            journals: journals,
          });
        }
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };

  /**
   * 如果给定的remarks,长度过长,将会截断
   * @param remarks
   * @returns {string}
   */
  getRemarks = (remarks, maxlength = 15) => {
    let str = remarks;
    if (str) {
      if (str.length > maxlength) {
        str = str.substr(0, maxlength) + '...';
      }
    } else {
      str = '';
    }
    return str;
  };

  render() {
    const dateCellRender = value => {
      const listData = this.getListData(value);
      return (
        <ul className="events">
          {listData.map((item, index) => (
            <li
              key={index}
              onClick={event => {
                event.stopPropagation();
                this.handleJournalItemClick(item);
              }}
            >
              <Badge status={'success'} text={this.getRemarks(item['remarks'], 15)} />
            </li>
          ))}
        </ul>
      );
    };

    return (
      <JournalDiv>
        <Card bordered={true} title={'项目日志'}>
          <Row>
            <Col span={8}>
              <Button
                type="primary"
                style={{ marginRight: '8px' }}
                onClick={this.handleCreateBtnClick}
              >
                新建
              </Button>
            </Col>
            <Col span={16}>
              <div className={'header-right'}></div>
            </Col>
          </Row>
        </Card>
        <Card className={'body-card'}>
          <Calendar onPanelChange={this.handlePanelChange} dateCellRender={dateCellRender} />
        </Card>
        {/*新增*/}
        {this.state.createVisible ? (
          <Create
            wrappedComponentRef={createView => (this.createView = createView)}
            visible={this.state.createVisible}
            projects={this.state.projects}
            username={this.props.currentUser.username}
            onClose={this.handleCreateViewClose}
            onConfirmClick={this.handleCreateViewConfirmClick}
          ></Create>
        ) : null}
        {/*详情*/}
        {this.state.previewVisible && Object.keys(this.state.record).length > 0 ? (
          <Preview
            wrappedComponentRef={view => (this.previewView = view)}
            visible={this.state.previewVisible}
            record={this.state.record}
            onClose={this.handlePreviewViewClose}
            onDel={this.handleJournalDelClick}
          ></Preview>
        ) : null}
      </JournalDiv>
    );
  }

  /**
   *新增关闭按钮被点击
   */
  handleCreateViewClose = e => {
    this.setState({
      createVisible: false,
    });
  };

  /**
   * 详情页面关闭
   * @param e
   */
  handlePreviewViewClose = e => {
    this.setState({
      previewVisible: false,
    });
  };

  /**
   * 删除日志
   * @param id
   */
  handleJournalDelClick = id => {
    if (this.props.isDeling) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('projectjournal/deleteJournalById', {
      id: id,
    })
      .then(value => {
        hide();
        const { success, message } = value;
        if (success) {
          this.successMessage(message);
        } else {
          this.errorMessage('出错了');
        }
        this.setState({ previewVisible: false }, () => {
          this.selectAllJournalsByUser();
        });
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };

  /**
   * 新增视图确认按钮被点击
   * @param data
   */
  handleCreateViewConfirmClick = ({ data }) => {
    if (this.props.isCreating) {
      return;
    }
    data['create_by'] = this.props.currentUser['id'];
    // console.log(JSON.stringify(data));
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('projectjournal/create', { ...data })
      .then(value => {
        hide();
        const { success, message } = value;
        if (success) {
          this.successMessage(message);
        } else {
          this.errorMessage('出错了');
        }
        this.setState({ createVisible: false }, () => {
          this.selectAllJournalsByUser();
        });
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };

  /**
   * 新增按钮被点击
   */
  handleCreateBtnClick = () => {
    this.setState({
      createVisible: true,
    });
  };

  /**
   * 日历切换
   * @param value
   * @param mode
   */
  handlePanelChange = (value, mode) => {
    // console.log(value.format('M'));
    this.setState(
      {
        searchDate: value.toDate(),
      },
      () => {
        this.selectAllJournalsByUser();
      }
    );
  };

  getListData = value => {
    let listData;
    const key = value.date();
    const { journals } = this.state;
    listData = journals[`${key}`];
    return listData || [];
  };

  handleJournalItemClick = item => {
    this.setState({
      previewVisible: true,
      record: item,
    });
  };
}

export default Journal;
